package com.sy.controller;

import com.sy.exception.PhoneException;
import com.sy.form.AddressForm;
import com.sy.service.AddressService;
import com.sy.utils.ResultVOUtil;
import com.sy.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * Created by 时宇 on 2021-08-06 17:36
 */
@RestController
@RequestMapping("/address")
@Slf4j
@CrossOrigin
public class AddressHandler {
    @Resource
    private AddressService addressService;

    @GetMapping("/list")
    public ResultVO list() {
        return ResultVOUtil.success(addressService.findAll());
    }

    @PostMapping("/create")     //restful规范，添加用post
    public ResultVO create(@Valid @RequestBody AddressForm addressForm, BindingResult bindingResult) {
        //@RequestBody把前端传来的json数据解析成java对象
        //@Valid校验，错误信息传到bindingResult
        if (bindingResult.hasErrors()) {
            log.error("【添加地址】参数错误,addressForm={}", addressForm);
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }

        addressService.saveOrUpdate(addressForm);

        return ResultVOUtil.success(null);
    }

    @PutMapping("/update")     //restful规范，修改用put
    public ResultVO update(@Valid @RequestBody AddressForm addressForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【修改地址】参数错误,addressForm={}", addressForm);
            throw new PhoneException(bindingResult.getFieldError().getDefaultMessage());
        }

        addressService.saveOrUpdate(addressForm);

        return ResultVOUtil.success(null);
    }
}